import { useMutation, useQuery } from "@apollo/client";
import {
  getOrganizationInfo,
  getOrganizations,
  getOrganizations_select,
  updateOrganization,
} from "../../graphql/organization";
import {
  OrganizationsType_query,
  OrganizationType_mutation,
  OrganizationType_query,
} from "../../types/organization";
import { message } from "antd";

export const useGetOrganizations_service = (
  pageNum: number,
  pageSize: number
) => {
  const { loading, refetch, data } = useQuery<OrganizationsType_query>(
    getOrganizations,
    {
      variables: { page: { pageNum, pageSize } },
    }
  );
  return {
    loading,
    refetch,
    page: data?.getOrganizations.page,
    data: data?.getOrganizations.data,
  };
};

export const useGetOrganizations_select_service = (
  name: string,
  pageNum = 1,
  pageSize = 10000000
) => {
  const { loading, refetch, data } = useQuery<OrganizationsType_query>(
    getOrganizations_select,
    {
      variables: { page: { pageNum, pageSize }, name },
    }
  );
  return {
    loading,
    refetch,
    data: data?.getOrganizations.data,
  };
};

export const useGetOrganizationInfo_service = (id: string) => {
  const { loading, refetch, data } = useQuery<OrganizationType_query>(
    getOrganizationInfo,
    {
      variables: {
        id,
      },
    }
  );
  return {
    loading,
    refetch,
    data: data?.getOrganizationInfo.data,
  };
};

export const useUpdateOrg_service = (): {
  editLoading: boolean;
  handleEdit: (
    id: string | undefined,
    params: {
      identityCardBackImg: string;
      businessLicense: string;
      address?: string;
      orgOtherImg: { url: string }[];
      orgRoomImg: { url: string }[];
      latitude?: string;
      description?: string;
      tags: string;
      orgFrontImg: { url: string }[];
      identityCardFrontImg: string;
      name?: string;
      logo: string;
      tel?: string;
      id?: string;
      longitude?: string;
    }
  ) => Promise<void>;
} => {
  const [edit, { loading }] = useMutation(updateOrganization);

  const handleEdit = async (id: number, params: OrganizationType_mutation) => {
    const { data } = await edit({
      variables: {
        id,
        params,
      },
    });
    void message.info(data.commitOrganization.message);
  };

  return { handleEdit, editLoading: loading };
};
